<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class VillagePublish extends Model
{
    use SoftDeletes;
    protected $table = 'village_publish';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];

    protected $appends = ['list_img_url', 'imgs_url','content_into', 'zaned', 'liked', 'collected','followed'];


    public function village_pub_admin_author()
    {
        return $this -> hasOne(AdminUsers::class,'id','admin_id');
    }

    // 所属地区
    public function region_info()
    {
        return $this->hasOne('\App\Models\SystemRegion', 'id', 'region_id');
    }

    public function village_pub_author()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }


    public function getContentIntoAttribute()
    {
        $content_intro = strip_tags($this->pub_content);
        $content_intro = str_replace('\r', '', $content_intro);
        $content_intro = str_replace('\n', '', $content_intro);
        return $content_intro;
    }

    public function getListImgUrlAttribute()
    {
        return config('app.img_url') . $this -> list_img;
    }


    public function getZanedAttribute()
    {

        if(!$user_id = auth() -> id()){
            return false;
        }

        return $zaned = VillagePubOperateLogs::where('village_pub_id',$this->id) -> where('user_id',$user_id) -> where('operate_type',2) -> first()
            ? true : false;
    }

    public function getLikedAttribute()
    {

        if(!$user_id = auth() -> id()){
            return false;
        }
        // 图文1、商品2、乡村在线3
        $obj_types = 3;

        return $liked = UserCollect::where('obj_id',$this->id) -> where('user_id',$user_id) -> where('obj_types',$obj_types) -> where('types',1) -> first()
            ? true : false;
    }


    // 是否被关注
    public function getFollowedAttribute()
    {
        if(!$user_id = auth() -> id()){
            return false;
        }

        if(!$this -> admin_id){
            return false;
        }

        return $followed = UserFollow::where('follow_admin_id',$this -> admin_id) -> where('user_id',$user_id) -> first()
            ? true : false;
    }


    // 是否被收藏
    public function getCollectedAttribute()
    {
        if(!$user_id = auth() -> id()){
            return false;
        }
        // 文章1、商品2、乡村在线3
        $obj_types =  3 ;

        return $collected = UserCollect::where('obj_id',$this->id) -> where('user_id',$user_id) -> where('obj_types',$obj_types) -> where('types',2) -> first()
            ? true : false;
    }


    public function getImgsUrlAttribute()
    {
        $newarr = [];
        if($this -> attributes['imgs']){
            $arr = json_decode($this -> attributes['imgs']);
            foreach($arr as $v){
                $newarr[] = config('app.img_url') . $v;
            }
        }
        return $newarr;
    }




    public static function village_pub_list($regionId,$pagesize = 5,$order = 1){
        $query = self::query();


        $query->where(function ($query_region) use ($regionId) {
            if ($regionId > 0) {
                $query_region->where('region_id', $regionId);
            }
        });

        $query -> where('is_show',1);


        if ($order == 1) {
            $query->orderBy('is_top', 'desc');
            $query->orderBy('weight', 'desc');
            $query->orderBy('passed_at', 'desc');
        }

        $query->with(['village_pub_admin_author:id,name,avatar']);
        $dataList = $query->paginate($pagesize);

        return $dataList;
    }

    // 存储数据
    public static function store($param)
    {
        if($param['imgs']){
            $imgs = explode(',',$param['imgs']);
            $param['list_img'] = $imgs[0];
            $param['imgs'] = json_encode($imgs);
        }
        $param['user_id'] = auth() -> id();
        $param['is_show'] = 1;

        return self::create($param);

    }



    // 乡村在线被各种操作  阅读1、点赞2、喜欢3、收藏4、分享5、作者关注6
    public static function village_pub_operated($village_pub_id, $type)
    {

        $inc_fields = [1 => 'read_num', 2 => 'zan_num', 3 => 'like_num', 4 => 'collect_num', 5 => 'share_num'];

        switch($type){
            case 1:

                VillagePubOperateLogs::log(['id' => $village_pub_id, 'type' => $type]); //记录日志
                self::where('id', $village_pub_id) -> increment($inc_fields[$type]);
                $res = 1;
                break;
            case 2:

                $villagePub = self::where('id', $village_pub_id);
                $logData = [
                    'village_pub_id'   => $village_pub_id,
                    'user_id'      => auth() -> id(),
                    'operate_type' => $type,
                ];
                if(VillagePubOperateLogs::where($logData) -> first()){
                    $res = $villagePub -> decrement($inc_fields[$type]);
                }else{
                    $res = $villagePub -> increment($inc_fields[$type]);
                }
                VillagePubOperateLogs::log(['id' => $village_pub_id, 'type' => $type]);
                break;
            case 3:

                $collect_data = [
                    'obj_id' => $village_pub_id,
                    'obj_types' =>  3,
                    'types' =>  1
                ];
                $res = UserCollect::up($collect_data);
                VillagePubOperateLogs::log(['id' => $village_pub_id, 'type' => $type]);
                break;
            case 4:

                $collect_data = [
                    'obj_id' => $village_pub_id,
                    'obj_types' => 3,
                    'types' => 2
                ];
                $res = UserCollect::up($collect_data);
                VillagePubOperateLogs::log(['id' => $village_pub_id, 'type' => $type]); //记录日志
                break;
            case 5:

                $res = self::where('id', $village_pub_id) -> increment($inc_fields[$type]);
                VillagePubOperateLogs::log(['id' => $village_pub_id, 'type' => $type]); //记录日志
                break;

            /*case 6:
                $user_id = auth() -> id();

                // 监测用户是否已被关注  已被关注的，取消关注
                $followed_user_id = self::where('id',$village_pub_id) -> value('admin_id');
                $res = UserFollow::followOrCancel($user_id,$followed_user_id);

                VillagePubOperateLogs::log(['id' => $village_pub_id, 'type' => $type]); //记录日志
                break;*/
        }


        return $res;

    }

    /**
     * PC端获得农品助力列表
     * @param array $whereData
     * @param int $pagesize
     * @return mixed
     */
    public static function pc_village_publish_lists($whereData = [], $pagesize = 20)
    {
        $query = VillagePublish::where('is_show', 1);
        $query->where('check_status', 2);

        $query->with(['region_info', 'village_pub_admin_author', 'village_pub_author']);
        $query->orderBy('is_top', 'desc');
        $query->orderBy('weight', 'desc');
        $query->orderBy('id', 'desc');
        $village_publish = $query->paginate($pagesize);

        return $village_publish;
    }

}
